<?php
/*
 *      _______ _     _       _     _____ __  __ ______
 *     |__   __| |   (_)     | |   / ____|  \/  |  ____|
 *        | |  | |__  _ _ __ | | _| |    | \  / | |__
 *        | |  | '_ \| | '_ \| |/ / |    | |\/| |  __|
 *        | |  | | | | | | | |   <| |____| |  | | |
 *        |_|  |_| |_|_|_| |_|_|\_\\_____|_|  |_|_|
 */
/*
 *     _________  ___  ___  ___  ________   ___  __    ________  _____ ______   ________
 *    |\___   ___\\  \|\  \|\  \|\   ___  \|\  \|\  \ |\   ____\|\   _ \  _   \|\  _____\
 *    \|___ \  \_\ \  \\\  \ \  \ \  \\ \  \ \  \/  /|\ \  \___|\ \  \\\__\ \  \ \  \__/
 *         \ \  \ \ \   __  \ \  \ \  \\ \  \ \   ___  \ \  \    \ \  \\|__| \  \ \   __\
 *          \ \  \ \ \  \ \  \ \  \ \  \\ \  \ \  \\ \  \ \  \____\ \  \    \ \  \ \  \_|
 *           \ \__\ \ \__\ \__\ \__\ \__\\ \__\ \__\\ \__\ \_______\ \__\    \ \__\ \__\
 *            \|__|  \|__|\|__|\|__|\|__| \|__|\|__| \|__|\|_______|\|__|     \|__|\|__|
 */
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2014 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: Dean <zxxjjforever@163.com>
// +----------------------------------------------------------------------
namespace Portal\Controller;
use Common\Controller\HomebaseController;
use Label\Model\CategoryModel;
use Portal\Model\PostsModel;
use Think\Cache\Driver\Redis;
use Wx\Controller\WxPayController;

/**
 * 首页
 */
class IndexController extends HomebaseController {

    public function test()
    {
//        $contents = file_get_contents('http://23.252.161.21:8686/8group/a.jpg');
//        var_dump("" . $contents . "");

//        $rs = ['status' => 1];
//        set_time_limit(0);
//        ob_end_clean();
//        header("Connection: close");
//        header("HTTP/1.1 200 OK");
////        header("Content-Type: application/json;charset=utf-8");// 如果前端要的是json则添加，默认是返回的html/text
//        ob_start();
//        echo json_encode($rs);// 输出结果到前端
//        $size = ob_get_length();
//        header("Content-Length: $size");
//        ob_end_flush();
//        flush();
//        if (function_exists("fastcgi_finish_request")) { // yii或yaf默认不会立即输出，加上此句即可（前提是用的fpm）
//            fastcgi_finish_request(); // 响应完成, 立即返回到前端,关闭连接
//        }
//        sleep(2);
//        ignore_user_abort(true);// 在关闭连接后，继续运行php脚本
//        set_time_limit(0);
//
//        $redis  = Redis::getinstance();
//        $key    = "my_list";
//        $redis->select(1);
//        for ($i = 0; $i < 100; $i++) {
//            $re = $redis->blpop($key, 30);
//            writeFile($re);
//            if ($re) {
//                writeFile("get content success");
//            } else {
//                writeFile("redis time out ");
//                break;
//            }
//        }

//        $num = preg_match('/\\w/', 'fdajskjdf', $match);
//        var_dump($num);
//        var_dump($match);
//        $num = preg_match_all('/a(\d)*/', 'fdajskjdf', $match1);
//        var_dump($num);
//        var_dump($match1);

//        $redis = Redis::getinstance();
//        $redis->select(1);
//        $redis->rpush('my_list', json_encode(['name' => 'glq', 'age' => 27]), json_encode(['name' => 'zxj', 'age' => 26]));
//        $info = $redis->lindex('my_list', 1);
//        var_dump($info);
//        var_dump(json_decode($info)->name);

//        $redis->hset('myhash', 'name', 'glq');
//        $redis->hmset('myhash', ['age' => 27, 'sex' => 1]);
//        var_dump($redis->hmget('myhash', ['name', 'sex']));

//        $redis->set('glq', 10, 5 * 60);
//        var_dump($redis->get('glq'));
//        $redis->incr('glq');
//        var_dump($redis->get('glq'));
//        var_dump($redis->ttl('glq'));

//        var_dump(strtotime(date("Y-m-d", strtotime("+0 day"))));

//        var_dump(sprintf("%06d", 3));
//        var_dump(date("YmdHis") . sprintf("%06d", 3));

//        $task_key = [];
//        in_array(1, $task_key) ? $task_key : array_push($task_key, 1);
//        in_array(2, $task_key) ? $task_key : array_push($task_key, 2);
//        in_array(1, $task_key) ? $task_key : array_push($task_key, 1);
//        var_dump($task_key);

//        var_dump(round(1.334, 2));

//        $array = array(
//            array('id'=>'3','name'=>'tom'),
//            array('id'=>'5','name'=>'jerry'),
//            array('id'=>'24','name'=>'spike')
//        );
//        $array1 = array(
//            array('id'=>'3','name'=>'tom', 'sex'=> 1),
//            array('id'=>'5','name'=>'jerry', 'sex'=> 0),
//            array('id'=>'24','name'=>'spike', 'sex'=> 2),
//        );
//        $newArray = array_column($array,NULL,'id');
//        var_dump($newArray);
//        $newArray1 = array_column($array1,NULL,'id');
//        var_dump($newArray1);
//        foreach ($newArray as $k => $v) {
//            if (key_exists($k, $newArray1)) {
//                $v['sex'] = $newArray1[$k]['sex'];
//                $newArray[$k] = $v;
//            }
//        }
//        var_dump($newArray);

//        $list = M('label')->where('id > label_type_id')->where(['label_type_id' => 14])->select();
//        var_dump($list);

//        var_dump(strtotime(date("Y-m-d 23:00:00", 1557893040)));

//        var_dump(time());
//        var_dump(get_week_start_end());

//        var_dump(M('users')->where(['id' => ['GT', 10]])->sum("id"));

//        $a = urlencode("http://www.rixins.com/index.php?g=a&m=b&a=c");
//        var_dump($a);

//        setcookie("glq", '123456');
//        var_dump($_COOKIE['glq']);
//        var_dump(cookie('glq'));
//        setcookie('glq', '', -1);
//        var_dump($_COOKIE['glq']);

//        $search_loction = "朝阳区青云店镇东店村青大路大东新村";
//        preg_match("/(.*?(市))?(.*?(区))(.*)/", $search_loction, $matchs);
//        var_dump($matchs);
//        $this->ajaxReturn(['status' =>1, 'name' => 'glq']);
    }

    public function test_mini_pay()
    {
        $this->display();
    }

    public function test_baidu_map()
    {
        // 获取地址信息的经纬度
//        $url    = "http://api.map.baidu.com/geocoding/v3/?address=北京市津南区七觉得村199号楼&output=json&ak=p1dVi5KCcYv1HEgLMtfLcHuNu0TRR97g";

        // 获取地点输入提示
        $url    = "http://api.map.baidu.com/place/v2/suggestion?query=百子&region=北京&city_limit=true&output=json&ak=p1dVi5KCcYv1HEgLMtfLcHuNu0TRR97g";
        $re     = curl_requestion($url);
        var_dump(json_decode($re['data'], true));
//        $this->display();
    }

    public function deal_xq_advertising()
    {
        $model          = M('xq_advertising');
//        $start          = 1300;
//        $xq_type_arr    = array('中高端住宅' => 1, '写字楼' => 2, '商住楼' => 3, '综合体' => 4);
//
//        $lists = $model->order("id asc")->limit($start, 100)->select();
//        foreach ($lists as $v) {
//            $v['xq_type']       = $xq_type_arr[$v['xq_type_desc']];
//            $v['build_time']    = date("Y-m-d", strtotime($v['build_time_desc']));
//            $url                = "http://api.map.baidu.com/geocoding/v3/?output=json&ak=p1dVi5KCcYv1HEgLMtfLcHuNu0TRR97g&address=北京市" . $v['xq_district'] . $v['xq_address'];
//            $re                 = curl_requestion($url);
//            if ($re['status']) {
//                $re             = json_decode($re['data'], true);
//                $v['lng']       = $re['result']['location']['lng'];
//                $v['lat']       = $re['result']['location']['lat'];
//            } else {
//                writeFile("get location error");
//                writeFile($re);
//            }
//            $model->where(['id' => $v['id']])->save($v);
//        }

//        $model  = M('xq_ad_one');
//        $where  = ['lng' => 0];
//        $start  = I('get.start', 0);
//        $lists  = $model->where($where)->order("id asc")->limit($start, 100)->select();
//        foreach ($lists as $v) {
//            var_dump($v['id']);
//            $url                = "http://api.map.baidu.com/geocoding/v3/?output=json&ak=p1dVi5KCcYv1HEgLMtfLcHuNu0TRR97g&address=北京市" . $v['xq_district'] . $v['xq_address'];
//            $re                 = curl_requestion($url);
//            if ($re['status']) {
//                $re             = json_decode($re['data'], true);
//                $v['lng']       = $re['result']['location']['lng'];
//                $v['lat']       = $re['result']['location']['lat'];
//            } else {
//                writeFile("get location error");
//                writeFile($re);
//            }
//            $model->where(['id' => $v['id']])->save($v);
//        }
//        echo 'finish - ' . $start;

//        $model          = M('xq_advertising');
//        $model_one      = M('xq_ad_one');
//        $model_two      = M('xq_ad_two');
//        $start          = I('get.start', 0);
//        $xq_type_arr    = array('中高端住宅' => 1, '写字楼' => 2, '商住楼' => 3, '综合体' => 4);
//        $lists          = $model_one->order("id asc")->limit($start, 500)->select();
//
//        foreach ($lists as $v) {
//            $v['xq_type']       = $xq_type_arr[$v['xq_type_desc']];
//            $v['build_time']    = date("Y-m-d", strtotime($v['build_time_desc']));
//            if (strpos($v['price_desc'], '以上') > 0) {
//                preg_match("/(\d*)以上/", $v['price_desc'], $match);
//                var_dump($match);
//                $v['min_price'] = $match[1];
//                $v['max_price'] = 99999999;
//            }
//            if (strpos($v['price_desc'], "-") > 0) {
//                $temp = explode("-", $v['price_desc']);
//                $v['min_price'] = $temp[0];
//                $v['max_price'] = $temp[1];
//            }
//            $temp = $model->where(['xq_name' => $v['xq_name']])->find();
//            if ($temp) {
//                $v['lng']       = $temp['lng'];
//                $v['lat']       = $temp['lat'];
//                $v['build_num'] = $temp['build_num'];
//            }
//            $model_one->where(['id' => $v['id']])->save($v);
//        }
//        echo "finish - " . $start;
    }
    
    public function send_wx_template_msg_test()
    {
//        oerkS1SSS4aWWiC06K4kznj56SvA -- 开放平台
//        oINfj1GVZI0ChXbp8ZadiuvSfxRQ -- 公众号
        $openid         = 'oINfj1GVZI0ChXbp8ZadiuvSfxRQ';
        $template_id    = 'R5241KEt1nRrEqe0P1fT2jo9QSTYjGrCbz5YtSmKTSk';
        $data           = array(
            'touser'            => $openid,
            'template_id'       => $template_id,
            "miniprogram"       => array(
                "appid"         => "wx19ae88f77bba2fe5",
                "pagepath"      => "index?foo=bar"
            ),
            'data'              => array(
                'first'         => array(
                    'value'     => urlencode('恭喜你预约行家咨询成功'),
                    'color'     => "#173177",
                ),
                'keyword1'      => array(
                    'value'     => urlencode('2019.3.29 14:00'),
                    'color'     => "#173177",
                ),
                'keyword2'      => array(
                    'value'     => urlencode('2019.3.29 16:00'),
                    'color'     => "#173177",
                ),
                'remark'        => array(
                    'value'     => urlencode('请提前5分钟做好准备！'),
                    'color'     => "#173177",
                ),
            ),
        );

        send_wx_template_msg(urldecode(json_encode($data)));
    }
	
	public function index() {
        $page = I('get.' . C('VAR_PAGE'), 0, 'intval');
        // 首页列表数据预加载
        if ($page <= 1) {
            // 早报
            $week = date('w', time());
            if ($week == 0) {
                $start_time = strtotime(date('Y-m-d 00:00:00', time())) - 24 * 3600 * 2;
                $end_time   = strtotime(date('Y-m-d 23:59:59', time())) - 24 * 3600 * 2;
            } elseif ($week == 6) {
                $start_time = strtotime(date('Y-m-d 00:00:00', time())) - 24 * 3600;
                $end_time   = strtotime(date('Y-m-d 23:59:59', time())) - 24 * 3600;
            } else {
                $start_time = time();
                $end_time   = time();
            }
            $where = [
                'post_type'     => PostsModel::POST_TYPE_DAILY_REPORT,
                'post_status'   => PostsModel::POST_STATUS_NORMAL,
                'post_date'     => [['LT', date('Y-m-d 23:59:59', $end_time)], ['EGT', date('Y-m-d 00:00:00', $start_time)]],
            ];
            $report = M('posts')->where($where)->find();
            $this->assign('report', $report);
            // 列表之间的广告位
            $advertisement_between  = get_ad_by_position(CategoryModel::SLIDESHOW_POSITION_INDEX_BETWEEN_ARTICLE);
            $this->assign('advertisement_between', $advertisement_between);
            // 文章
            $types = getCategoryTypes(CategoryModel::CATEGORY_TYPE_ARTICLE);
            foreach ($types as $k => $v) {
                $lists[$v['id']] = sp_get_post_by_category_id($v['id']);
            }
            $this->assign('lists', $lists);
//            // 快讯
//            $where = array(
//                'p.post_type'       => PostsModel::POST_TYPE_NEWS,
//                'p.post_status'     => PostsModel::POST_STATUS_NORMAL,
//            );
//            $model = M('posts');
//            $count = $model->alias('p')->where($where)->count();
//            $page  = $this->page($count, 20);
//
//            $news_lists = M('posts')
//                ->alias('p')
//                ->where($where)
//                ->limit($page->firstRow, $page->listRows)
//                ->order("p.post_date desc")
//                ->select();
//            $this->assign('news_lists', $news_lists);
        }

	    $this->assign('cat_id', I('cat_id', 0, 'intval'));
        $this->display(":index");
    }

    // 研习社首页
    public function moduleIndex()
    {
//        // 问答
//        $where = array(
//            'p.post_type'       => PostsModel::POST_TYPE_DISCUSSION_QUESTION,
//            'p.post_status'     => PostsModel::POST_STATUS_NORMAL,
//        );
//        $question = M('posts')
//            ->alias('p')
//            ->where($where)
//            ->field('p.*, (SELECT GROUP_CONCAT(u.avatar) FROM rx_posts p1 LEFT JOIN rx_users u ON u.id = p1.post_author WHERE p1.post_type = ' . PostsModel::POST_TYPE_DISCUSSION_ANSWER . ' and p1.post_status = ' . PostsModel::POST_STATUS_NORMAL . ' and p1.question_id = p.id) as answer_avatars')
//            ->order('p.post_order desc, p.post_date desc')
//            ->limit(6)
//            ->select();
//
//        foreach ($question as $k => $v) {
//            // 点赞
//            if (empty($v['total_like'])) {
//                $v['total_like'] = 0;
//            }
//
//            if (empty($v['answer_avatars'])) {
//                $v['answer_avatars'] = [];
//            } else {
//                $org_avatars = explode(',', $v['answer_avatars']);
//                $has_avatars = array();
//                foreach ($org_avatars as $v1) {
//                    if (!in_array($v1, $has_avatars)) {
//                        $has_avatars[] = $v1;
//                    }
//                }
//                $v['answer_avatars'] = array();
//                foreach ($has_avatars as $v1) {
//                    $v['answer_avatars'][] = sp_get_user_avatar_url($v1);
//                }
//                $v['answer_avatars'] = array_slice($v['answer_avatars'], 0, 5);
//            }
//            $question[$k] = $v;
//        }
//        $this->assign('question', $question);
//
//        // 项目
//        $xiaoqus = M('xiaoqu')
//            ->field("id, name, imgs, addr, build_time, manager_company, (select group_concat(name) from rx_category where find_in_set(id, rx_xiaoqu.categorys)) as category_names")
//            ->limit(12)
//            ->select();
//        $this->assign('xiaoqus', $xiaoqus);
//
//        $this->display();


//        var_dump(C('MOBILE_TPL_ENABLED') && sp_is_mobile());exit;
        if(C('MOBILE_TPL_ENABLED') && sp_is_mobile()) {
            // 移动端
            $url = "https://app98mbqp3r6954.h5.xiaoeknow.com/content_page/eyJ0eXBlIjozLCJhcHBfaWQiOiJhcHA5OE1CcVAzUjY5NTQiLCJyZXNvdXJjZV90eXBlIjoiIiwicHJvZHVjdF9pZCI6InBfNWQxOTc0NDAyOWRkOF9ZYkFuQVB5diIsImNoYW5uZWxfaWQiOiIiLCJyZXNvdXJjZV9pZCI6IiJ9";
            header("Location:" . $url);exit();
        } else {
            // pc端
            $this->display();
        }
    }


    // 专栏作者列表页
    // ！！！！该方法不能换地址！！！！
    public function professor_list()
    {
        $model = M('professor');
        $where = [
            'p.status'      => 1,
            'p.del_time'    => 0,
        ];
        $field = "p.id, p.user_id, u.user_nicename, u.avatar, u.position, u.signature, u.user_login, u.company";

        $name = I('post.name', '', 'strval');
        if ($name) {
            $where['u.user_nicename'] = array('like', "%$name%");
        }

        $count = $model
            ->alias('p')
            ->join("__USERS__ u ON p.user_id = u.id")
            ->where($where)
            ->count();
        $page = $this->page($count, 10);

        $pf_list = $model
            ->alias('p')
            ->join("__USERS__ u ON p.user_id = u.id")
            ->where($where)
            ->field($field)
            ->limit($page->firstRow , $page->listRows)
            ->order("p.pf_order desc, p.created_at desc")
            ->cache("professor_list_" . $page->firstRow . '_' . $page->listRows, C('CACHE_EXPIRE'))
            ->select();

        $this->assign('pf_list', $pf_list);
        $this->assign("page", $page->show('default'));
        $this->assign('total_pages', ceil($count / 10));

        $this->display();
    }

    public function about_us()
    {
        $this->display();
    }

    public function join_us()
    {
        $this->display();
    }
}


